// 引入 express 框架 -> 需 npm 安装
var express = require('express');
const fs = require('fs');
const { Pool } = require('pg');
const directory = require('./views/directory');
const routineCall = require('./views/callProgram')
const saveService = require('./views/saveService')
const dataExport = require('./views/dataExport')
const fileConver = require('./views/fileConver')

// 读取配置文件，把配置保存到global
function getConfig () {
  const data = fs.readFileSync('./config.json', 'utf8')
  global.myConfig = JSON.parse(data)
}
// 目标表不存在需要创建
function createTable () {
  const serviceTable = global.myConfig.pool.serviceTable
  const logTable = global.myConfig.pool.logTable
  // 创建一个数据库连接池
  const pool = new Pool({
    user: global.myConfig.pool.user,
    host: global.myConfig.pool.host,
    database: global.myConfig.pool.database,
    password: global.myConfig.pool.password,
    port: global.myConfig.pool.port
  });
  global.pool = pool
  pool.query(`
  CREATE TABLE IF NOT EXISTS ${serviceTable} (
    id VARCHAR(255) NOT NULL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    info TEXT,
    path VARCHAR(255),
    type INT,
    section INT,
    scale TEXT,
    created_at VARCHAR(255)
  );
`, (err, res) => {
    if (err) {
      console.error(err);
    } else {
      console.log(`表${serviceTable}创建成功!`);
    }
  });
  pool.query(`
  CREATE TABLE IF NOT EXISTS ${logTable} (
    id VARCHAR(255) NOT NULL,
    time VARCHAR(255) NOT NULL,
    log TEXT
  );
`, (err, res) => {
    if (err) {
      console.error(err);
    } else {
      console.log(`表${logTable}创建成功!`);
    }
  });
}
/**
 * 初始化框架,并将初始化后的函数给予 '当前页面'全局变量 app
 * 也就是说, app 是 express 
 */
var app = express();
// 设置请求体大小限制为10MB
app.use(express.json({ limit: '10mb' }));

// 全局跨域中间件
const allowCrossDomain = (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*'); // 允许所有来源访问接口，你也可以根据需要指定特定的来源
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
};
// 设置 public 为静态文件的存放文件夹
app.use(allowCrossDomain)
app.use(express.urlencoded({ extended: true })); // 解析 URL 编码请求体
app.use('/public', express.static('public'));
app.use('/directory', directory)
app.use('/routineCall', routineCall)
app.use('/saveService', saveService)
app.use('/dataExport', dataExport)
app.use('/fileConver', fileConver)


/* 配置框架环境 E */
app.get('/', function (req, res) {
  res.send('Hello World');
})

// // 创建可写流
// const logStream = fs.createWriteStream('app.log', { flags: 'a' });

// // 重定向 console 输出到日志文件
// console.log = (message) => {
//   logStream.write(`[${new Date().toISOString()}] ${message}\n`);
// }

// 获取所有盘符
const getAllDriveLetters = () => {
  global.driveLetters = [];
  for (let i = 65; i <= 90; i++) {
    const driveLetter = String.fromCharCode(i);
    fs.access(driveLetter + ':\\', (err) => {
      if (err) {

      } else {
        app.use(`/${driveLetter}`, express.static(driveLetter + ':\\'))
        global.driveLetters.push(driveLetter);
      }
    });
  }
};

var server = app.listen(8086, function () {
  var host = server.address().address
  var port = server.address().port
  getConfig()
  createTable()
  getAllDriveLetters()
  console.log("Node.JS 服务器已启动，访问地址： http://%s:%s", host, port)
})